﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using PersistentManager.Query.Sql;
using PersistentManager.Query;
using PersistentManager.GAC;

namespace PersistentManager.Provider
{
    internal class MySqlProvider : DatabaseProvider
    {
        public MySqlProvider(DbTransaction transaction, DbConnection connection)
            : base(connection, transaction)
        {

        }

        public override SQLTokenizer GetFilteredQuerySyntax( SQLTokenizer Tokens , int index )
        {
            Tokens.AddFormatted( QueryPart.Appender , string.Format(" LIMIT {0} ", index));

            return Tokens;
        }

        public override int ExecuteUpdate( string query , ref DbParameter returnedValue , string columnName , List<DbParameter> parameters )
        {
            int update = ExecuteUpdate(query, parameters);
            returnedValue.Value = GetAutoGeneratedColumnValue();

            return update;
        }

        public object GetAutoGeneratedColumnValue()
        {
            return ExecuteScalar("SELECT LAST_INSERT_ID();");
        }

        public override string GetNamingStrategyString( )
        {
            return "`{0}`";
        }

        public override string GetParameterPrefix( )
        {
            return "?";
        }

        public override bool SupportsMultipleActiveReader
        {
            get
            {
                return false;
            }
        }

        public override DbDataReader Range( SQLTokenizer tokens , int StartRange , int Endrange , string query , List<DbParameter> parameters )
        {
            query = string.Concat( query , string.Format(" LIMIT {0}, {1}", StartRange , Endrange - StartRange ) );

            return GetDataReader( query , parameters );

        }

        public override DbParameter GetCommandParameter( string name , object value )
        {
            return ( DbParameter )GacLoader.GetParameter( new Guid( EmbeddedProviderGUID.MYSQL_GUID ) , name , value , true );
        }
    }
}